package com.nidu.demo.dept.executor.query;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.nidu.demo.dept.convertor.DepartmentCriteriaConvertor;
import com.nidu.demo.dept.dto.DepartmentListQry;
import com.nidu.demo.dept.dto.DepartmentTreeQry;
import com.nidu.demo.dept.convertor.DepartmentConvertor;
import com.nidu.demo.dept.dto.DepartmentCO;
import com.nidu.demo.dept.dto.DepartmentTreeCO;
import com.nidu.demo.dept.model.DepartmentCriteria;
import com.nidu.demo.dept.util.DepartmentUtil;
import com.nidu.demo.dept.gateway.DepartmentGateway;
import com.nidu.demo.dept.model.Department;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 部门列表查询执行器
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class DepartmentListQryExe {

    private final DepartmentGateway gateway;

    private final DepartmentConvertor convertor;

    private final DepartmentCriteriaConvertor criteriaConvertor;

    public MultiResponse<DepartmentCO> execute(DepartmentListQry qry) {
        DepartmentCriteria criteria = criteriaConvertor.toDataObject(qry);
        List<Department> depts = gateway.listByCondition(criteria);
        if(CollUtil.isEmpty(depts)){
            return MultiResponse.of(Collections.emptyList());
        }
        List<DepartmentCO> deptCOS = convertor.toClientObjects(depts);
        return MultiResponse.of(deptCOS);
    }

    public MultiResponse<DepartmentTreeCO> execute(DepartmentTreeQry qry) {
        // 1. 查询部门列表
        DepartmentCriteria criteria = criteriaConvertor.toDataObject(qry);
        List<Department> depts = gateway.treeByCondition(criteria);
        if (CollUtil.isEmpty(depts)) {
            return MultiResponse.of(Collections.emptyList());
        }
        // 2. 转换为树形结构对象
        List<DepartmentTreeCO> deptTreeCOs = convertor.toTreeClientObjects(depts);
        return MultiResponse.of(DepartmentUtil.buildDeptTree(deptTreeCOs));
    }
}